import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
  HttpStatus,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Response } from 'express';

export interface ResponseFormat<T> {
  success: boolean;
  code: number;
  message: string;
  data: T;
  timestamp: string;
}

@Injectable()
export class ResponseInterceptor<T> implements NestInterceptor<T, ResponseFormat<T>> {
  intercept(context: ExecutionContext, next: CallHandler): Observable<ResponseFormat<T>> {
    const ctx = context.switchToHttp();
    const response = ctx.getResponse<Response>();
    const statusCode = response.statusCode || HttpStatus.OK;
    
    return next.handle().pipe(
      map((data) => {
        // 处理特殊情况：如果返回值已经是标准格式，则直接返回
        if (
          data &&
          typeof data === 'object' &&
          'success' in data &&
          'code' in data &&
          'message' in data
        ) {
          return data;
        }
        
        // 处理特殊情况：如果是删除操作返回的消息对象
        if (data && typeof data === 'object' && 'message' in data && Object.keys(data).length === 1) {
          return {
            success: true,
            code: statusCode,
            message: data.message,
            data: null,
            timestamp: new Date().toISOString(),
          };
        }
        
        // 标准格式
        return {
          success: true,
          code: statusCode,
          message: '请求成功',
          data,
          timestamp: new Date().toISOString(),
        };
      }),
    );
  }
} 